package com.zmn.oms.zmn.business.impl.chan;

import com.jdwl.open.api.sdk.internal.fastjson.JSON;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.common.exception.chan.ChannelFacadeException;
import com.zmn.oms.model.entity.chan.FacadeMessage;
import com.zmn.oms.model.entity.chan.FacadeMessageDoc;
import com.zmn.oms.services.interfaces.chan.FacadeMessageService;
import com.zmn.oms.zmn.business.interfaces.chan.FacadeMessageBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2020/12/29 22:01
 */
@Slf4j
@Service("facadeMessageBService")
public class FacadeMessageBServiceImpl implements FacadeMessageBService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private FacadeMessageService facadeMessageService;

    @Override
    public void save(FacadeMessage facadeMessage) throws ChannelFacadeException {
        if (facadeMessage.getCreateTime() == null) {
            facadeMessage.setCreateTime(new Date());
        }

        FacadeMessageDoc facadeMessageDoc = null;
        try {
            facadeMessageDoc = BeanMapper.map(facadeMessage, FacadeMessageDoc.class);
            mongoTemplate.save(facadeMessageDoc);
            return;
        } catch (Exception e) {
            log.error(String.format("渠道门户消息保存失败（MongoDB）：%s，FacadeMessageDoc=[%s]",
                    e.getMessage(), JSON.toJSONString(facadeMessageDoc)), e);
        }

        // MongoDB保存失败，临时存储在MySQL中
        try {
            facadeMessageService.save(facadeMessage);
            return;
        } catch (Exception e) {
            log.error(String.format("渠道门户消息保存失败（MySQL）：%s，FacadeMessage=[%s]",
                    e.getMessage(), JSON.toJSONString(facadeMessage)), e);
        }

        throw new ChannelFacadeException("渠道门户消息保存失败");
    }

    @Override
    public List<FacadeMessage> listByClueId(long clueId) {
        List<FacadeMessage> facadeMessages = null;

        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and("clueId").is(clueId);
        query.addCriteria(criteria);
        List<FacadeMessageDoc> facadeMessageDocs = mongoTemplate.find(query, FacadeMessageDoc.class);
        if (facadeMessageDocs != null) {
            facadeMessages = BeanMapper.mapList(facadeMessageDocs, FacadeMessage.class);
        }
        // TODO -lhl 保存失败时存储在临时位置的数据待提取

        return facadeMessages;
    }

    @Override
    public FacadeMessage findByClueIdAndMsgNo(long clueId, int msgNo) {
        FacadeMessage facadeMessage = null;

        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and("clueId").is(clueId);
        criteria.and("messageNo").is(msgNo);
        query.addCriteria(criteria);
        List<FacadeMessageDoc> facadeMessageDocs = mongoTemplate.find(query, FacadeMessageDoc.class);
        if (facadeMessageDocs != null && !facadeMessageDocs.isEmpty()) {
            facadeMessage = BeanMapper.map(facadeMessageDocs.get(0), FacadeMessage.class);
        }
        // 保存失败时去临时位置查找
        if (facadeMessage == null) {
            facadeMessage = facadeMessageService.findByClueIdAndMsgNo(clueId, msgNo);
        }

        return facadeMessage;
    }
}
